import React, { useState, useEffect, useRef } from 'react';
import { Form, Tabs, Row, Col, Button, message } from 'antd';
import DefineInterface from './DefineInterface';
import DefineReturn from './DefineReturn';
import services from '../../../../../services/api';
import '../index.less';
import { cloneDeep } from 'lodash';
import { connect } from 'react-redux';

const dataSourceType = 1;

const initValue = {
  dataSourceType,
  feeType: 0,
  priceJson: '{}',
  returningMaps: [],
};

const DatabaseInterfaceManage = (props) => {
  const { form } = props;
  const { validateFieldsAndScroll } = form;
  const [activeKey, setActiveKey] = useState('0');
  const [value, setValue] = useState(initValue);
  const [hasSet, setHasSet] = useState(false);
  const defineInterfaceRef = useRef();
  const id = props.match.params.id;

  useEffect(() => {
    props.dispatch({ type: 'pageClose/waringAdd' });
    return () => props.dispatch({ type: 'pageClose/waringReduce' });
  })

  useEffect(() => {
    id && getInnerInterfaceDetail();
  }, []);

  const getInnerInterfaceDetail = async () => {
    const { code, msg, data } = await services.interfaceManage.detail(id);
    if (code) return message.error(msg);
    const { bankDatabaseConnection } = data;
    data['databaseConnectionId'] = bankDatabaseConnection.id;
    setValue((prevState) => ({
      ...prevState,
      ...data,
    }));
  };

  const onChangeReturningMaps = (val, index, key) => {
    const temp = cloneDeep(value.returningMaps);
    if (key === 'innerPath' || key === 'thirdPath') {
      const new_val = val.match(/[0-9a-zA-Z_.]{1,}/);
      const tempVal = new_val ? new_val[0] : '';
      temp[index][key] = tempVal;
      key === 'innerPath' && (temp[index]['thirdPath'] = tempVal);
    } else {
      temp[index][key] = val;
    }
    setValue((prevState) => ({
      ...prevState,
      returningMaps: temp,
    }));
  };

  const onChangeRetuningMapsList = (returningMaps) => {
    setValue((prevState) => ({ ...prevState, returningMaps }));
  };

  const handleSubmit = () => {
    validateFieldsAndScroll(async (errors, formValues) => {
      if (!errors) {
        let params = {};
        try {
          params = {
            ...value,
            ...formValues,
            ...defineInterfaceRef.current.getDiData(),
          };
        } catch (error) {
          return message.warning(error);
        }
        const { code, msg } = await services.interfaceManage[id ? 'update' : 'add']({ id, ...params });
        if (!code) {
          message.success('操作成功');
          props.history.push('/dataGateway/databaseInterfaceManage');
        } else {
          message.error(msg);
        }
      }
    });
  };

  const handleNext = () => {
    form.validateFields(
      ['name', 'flag', 'isRateLimit', 'rateMax', 'groupId', 'feeType', 'databaseConnectionId'],
      (error) => {
        try {
          if (!error) {
            value.returningMaps.forEach((item) => {
              if (!item.innerPath) throw '出参不能为空';
            });
            setActiveKey('1');
            setHasSet(true)
          }
        } catch (err) {
          message.warning(err);
        }
      }
    );
  };

  return (
    <div className='add'>
      <Form>
        <Tabs style={{ width: '100%' }} activeKey={activeKey} onChange={(key) => setActiveKey(key)}>
          <Tabs.TabPane tab={'定义接口'} key='0' forceRender={true}>
            <div className='add_interface'>
              <DefineInterface
                {...props}
                ref={defineInterfaceRef}
                value={value}
                dataSourceType={dataSourceType}
                onChangeReturningMaps={onChangeReturningMaps}
                onChangeRetuningMapsList={onChangeRetuningMapsList}
              />
            </div>
          </Tabs.TabPane>
          {hasSet && (
            <Tabs.TabPane tab={'定义返回'} key='1' forceRender={true}>
              <div className='add_interface'>
                <DefineReturn
                  {...props}
                  value={value}
                  onChangeReturningMaps={onChangeReturningMaps}
                  onChangeRetuningMapsList={onChangeRetuningMapsList}
                />
              </div>
            </Tabs.TabPane>
          )}
        </Tabs>
        <Row type='flex' justify='start' className='operate_button'>
          <Col>
            {activeKey === '1' ? (
              <Button type='primary' onClick={handleSubmit}>
                保存
              </Button>
            ) : (
              <Button type='primary' onClick={handleNext}>
                下一步
              </Button>
            )}
          </Col>
        </Row>
      </Form>
    </div>
  );
};
export default connect()(Form.create()(DatabaseInterfaceManage));
